package com.fuhao.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.fuhao.core.base.BaseApiService;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.dto.output.PayMentTransacDTO;
import com.fuhao.pay.entity.PaymentChannelEntity;
import com.fuhao.pay.factory.StrategyFactory;
import com.fuhao.pay.mapper.PaymentChannelMapper;
import com.fuhao.pay.stragety.PayStrategy;
import com.fuhao.wx.WxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhang
 * @title: 支付上下文（策略模式+工厂模式）
 */
@RestController
public class PayContextServiceImpl extends BaseApiService<JSONObject> implements PayContextService{

    @Autowired
    private PaymentChannelMapper paymentChannelMapper;
    @Autowired
    private PayMentTransacInfoService payMentTransacInfoService;
    @Autowired
    private WxProperties wxProperties;

    @Override
    public BaseResponse<JSONObject> toPayContextHtml(String channelId, String payToken) {
        //1.根据支付渠道ID获取具体支付渠道的类的全路径Adress_Class
        PaymentChannelEntity paymentChannelEntity = paymentChannelMapper.selectBychannelId(channelId);
        if (paymentChannelEntity == null){
            return setResultError("未找到此支付渠道！");
        }
        //2.根据支付令牌获取支付参数
        BaseResponse<PayMentTransacDTO> payMentTransacDTO = payMentTransacInfoService.tokenByPayMentTransac(payToken);
        if(!isSuccess(payMentTransacDTO)){
            return setResultError(payMentTransacDTO.getMsg());
        }
        PayMentTransacDTO paydata = payMentTransacDTO.getData();//支付参数
        //3.根据策略模式+反射执行具体支付算法，返回html表单信息或二维码
        String classAddres = paymentChannelEntity.getClassAddres();//具体支付算法的类全路径
        PayStrategy payStrategy = StrategyFactory.getPayStrategy(classAddres);//获取支付具体行为
        //4.直接返回html
        String payHtml = payStrategy.toPayHtml(paymentChannelEntity, paydata);
        JSONObject data = new JSONObject();
        data.put("payHtml",payHtml);
        return setResultSuccess(data);
    }
}
